<template>
  <!-- This section should be hidden by default and shown when there are todos -->
  <section class="main">
    <input
      id="toggle-all"
      class="toggle-all"
      type="checkbox"
      v-model="checkAll"
    />
    <label for="toggle-all">Mark all as complete</label>
    <ul class="todo-list">
      <!-- These are here just to show the structure of the list items -->
      <!-- List items should get the class `editing` when editing and `completed` when marked as completed -->
      <li
        v-for="item in filterList"
        :key="item.id"
        :class="{ completed: item.done, editing: currentId === item.id }"
      >
        <div class="view">
          <input
            class="toggle"
            type="checkbox"
            :checked="item.done"
            @change="UPDATETODOSTATE(item.id)"
          />
          <label @dblclick="edit(item.id, item.todoName)">{{
            item.todoName
          }}</label>
          <button class="destroy" @click="DELONETODO(item.id)"></button>
        </div>
        <input
          class="edit"
          v-focus="currentId === item.id"
          v-model.lazy="todoName"
          @keyup.enter="updateTodo(item.id, todoName)"
          @blur="updateTodo(item.id, todoName)"
          @keyup.esc="escUpdate"
        />
      </li>
    </ul>
  </section>
</template>

<script>
import { mapState, mapMutations } from 'vuex'
export default {
  name: 'TodoMain',
  data() {
    return {
      currentId: 0,
      todoName: '',
    }
  },
  methods: {
    ...mapMutations('todoMvcModel', [
      'UPDATETODOSTATE',
      'DELONETODO',
      'UPDATETODO',
      'CHECKALLTODOS',
    ]),
    edit(id, name) {
      this.currentId = id
      this.todoName = name
    },
    updateTodo(id, todoName) {
      this.UPDATETODO({ id, todoName })
      this.currentId = 0
    },
    escUpdate() {
      this.currentId = 0
    },
  },
  computed: {
    ...mapState('todoMvcModel', ['todoList', 'showState']),
    checkAll: {
      get() {
        return this.todoList.every((item) => item.done)
      },
      set(val) {
        this.CHECKALLTODOS(val)
      },
    },
    filterList() {
      switch(this.$route.path){
        case "/home": 
          return this.todoList
        case "/active": 
          return this.todoList.filter((item) => !item.done)
        case "/completed": 
          return this.todoList.filter((item) => item.done)
      }
      
    },
  },
  directives: {
    focus: {
      update(el, binding) {
        if (binding.value) {
          el.focus()
        }
      },
    },
  },
}
</script>

<style></style>
